import React, {Component} from "react";
import {Switch, InputNumber, Tooltip, Modal, message, Form, Input, Button} from "antd";
import {QuestionCircleOutlined} from '@ant-design/icons';
import TheTable from "@/components/TheTable";
import TheTableExtend from "@/components/TheTableExtend";
import ThePagination from "@/components/ThePagination";
import TheButton from "@/components/TheButton";
import TheImage from "@/components/TheImage";
import TheQueryForm from "@/components/TheQueryForm";
// import "./style.scss";
import { cloneDeep } from 'lodash';
import {
    apiSpeciesPage,
    apiSpeciesPageAdd,
    apiSpeciesPageUpdate,
    apiSpeciesPageDel,
    apiSpeciesPageOne
} from "@/request/petDistinguish/breed.jsx";

const {confirm} = Modal;
//监听文本框，禁止输入回车和空格
const handleKeydown=(e)=>{
    if(e.keyCode===32 || e.keyCode===13){
        e.preventDefault();
        return;
    }
}
export default class ResourceManagement extends Component {
    constructor(props) {
        super(props)
        this.queryFormRef = React.createRef();
        this.FormRef = React.createRef();
        this.state = {
            columns: [
                {
                    title: "品种",
                    dataIndex: "speciesName",
                    key: "speciesName",
                },
                {
                    title: "排序",
                    dataIndex: "sorting",
                    key: "sorting",
                    width: '15%',
                    render: (text, record, index) => {
                        if (!record.flag){
                            return <Button type={'link'} onClick={()=>this.toOpenSort(index,record)}>{text === 999999999?"-":text}</Button>
                        }
                        else {
                            return (
                                <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
                                    <InputNumber min={0} precision={0} defaultValue={text === 999999999?1:text} onChange={this.valueInput}/>
                                    <TheButton style={{marginLeft: '10px'}} type='primary' size="middle" onClick={() => {
                                        this.sortChange(record)
                                    }}>确定</TheButton>
                                </div>
                            )
                        }
                    }
                },
                {
                    title: "操作",
                    fixed: 'right',
                    render: (text, record) => {
                        return (
                            <div>
                                <TheButton onClick={() => this.edit(record)}>编辑</TheButton>
                                <TheButton onClick={() => this.delete(record.petSpeciesId)}>删除</TheButton>
                            </div>
                        );
                    }
                },
            ],
            newColumns: [],
            pageData: {
                pageNo: 1,
                pageSize: 10,
            },
            dataSource: [],
            total: 1,
            searchOption: [
                {
                    field: "speciesName",
                    label: "品种",
                    placeholder: "请输入品种名称",
                    type: "Input",
                }
            ],
            form_show: true,
            queryForm: {
                speciesName: ''
            },
            close: false,
            sort: '',// 排序值
            petSpeciesId: '',//主键
            title: '',
            visible: false,
            speciesSort: props.type
        }
    }

    componentDidMount() {
        this.onColumnsFilter(this.state.columns)
        this.getData()
    }

    // 表格columns变化
    onColumnsFilter(value) {
        this.setState({newColumns: value})
    }

    // 列表
    getData = ()=> {
        let params = {
            ...this.state.queryForm,
            ...this.state.pageData,
            speciesSort: this.state.speciesSort
        }
        apiSpeciesPage(params).then(res=>{
            if (res.code === 0) {
                this.setState({
                    dataSource: res.data,
                    pageData: {
                        pageNo: res.pageNo,
                        pageSize: res.pageSize
                    },
                    total: res.totalCount
                })
            }
        })
    }

    // 排序输入框
    valueInput = (e) => {
        this.setState({sort: e})
    }
    toOpenSort = (i,v)=>{
        let { dataSource } = this.state
        dataSource.map((item,index)=>{
            // if (item.sorting === 999999999 && index === i){
            //     item.sorting = '-'
            // }
            item.flag = index === i;
            return item
        })

        this.setState({
            dataSource: cloneDeep(dataSource),
            sort: v.sorting === 999999999 ? 1 : v.sorting,
            // keywordId: v.keywordId,
            close: true
        })

    }
    editCancel = (e)=>{
        let t = e.target.localName;
        let { dataSource ,close} = this.state;
        if (t!=='svg' && t!=='button' && close && t!== 'path' && t!== 'input'){
            dataSource.map(item=>{
                return item.flag = false
            })
            this.setState({
                dataSource: cloneDeep(dataSource),
                close: false
            })
        }
    }

    // 排序修改
    async sortChange(record) {
        let params = {
            speciesSort: this.state.speciesSort,
            speciesName: record.speciesName,
            sorting: this.state.sort,
            petSpeciesId: record.petSpeciesId
        }
        apiSpeciesPageUpdate(params).then(res=>{
            if (res.code === 0){
                message.success('修改成功')
                this.handleCancel()
                this.getData()
            }
        })
    }

    edit = (record) => {
        this.setState({
            visible: true,
            title: '编辑品种',
            petSpeciesId: record.petSpeciesId
        }, () => {
            this.FormRef.current.setFieldsValue({
                ...record
            })
        })
    }

    // 删除资源配置
    delete(petSpeciesId) {
        React.$confirm({
            title: "提示",
            type: 'warning',
            content: "确认删除该宠物品种吗？",
            onOk: async () => {
                let res = await apiSpeciesPageDel({petSpeciesId})
                if (res.code === 0) {
                    message.success('删除成功！')
                    this.delToPageStatus()
                }
            }
        });
    }
    // 删除时如果分页余数为1跳转上一页数据
    delToPageStatus = ()=>{
        let { pageData,total } = this.state
        if ((total%pageData.pageSize) === 1){
            this.pageChange(pageData.pageNo-1,pageData.pageSize)
        }
        else {
            this.pageChange(pageData.pageNo,pageData.pageSize)
        }
    }
    // 分页切换
    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {pageNo, pageSize}
        }, () => {
            this.getData()
        });
    };
    onSearch = (values)=>{
        console.log(values)
        this.setState({
            queryForm: {
                speciesName: '',
                ...values
            }
        },()=>{
            this.getData()
        })
    }
    // 重置搜索
    onReset() {
        this.setState({
            queryForm: {
                speciesName: ''
            },
        }, () => {
            this.pageChange(1, 10)
        });
    }

    openModal = () => {
        this.setState({
            visible: true,
            title: '新增品种'
        })
    }
    handleOk = () => {
        this.FormRef.current.validateFields().then(values => {
            let params = {
                ...values,
                speciesSort: this.state.speciesSort
            }
            if (this.state.title === '新增品种'){
                apiSpeciesPageAdd(params).then(res=>{
                    if (res.code === 0){
                        message.success('新建成功')
                        this.handleCancel()
                        this.getData()
                    }
                })
            }else {
                params.petSpeciesId = this.state.petSpeciesId
                apiSpeciesPageUpdate(params).then(res=>{
                    if (res.code === 0){
                        message.success('修改成功')
                        this.handleCancel()
                        this.getData()
                    }
                })
            }
        })
    }
    handleCancel = () => {
        this.setState({
            visible: false
        },()=>{
            if(this.FormRef.current !== null){
                this.FormRef.current.resetFields()
            }
        })
    }

    render() {
        const {columns, dataSource, newColumns, pageData, total, form_show, searchOption, title, visible} = this.state
        return (
            <div onClick={(e)=>this.editCancel(e)}>
                <TheQueryForm
                    ref={(ref) => (this.queryFormRef = ref)}
                    show={form_show}
                    option={searchOption}
                    onGetValues={(values) => this.onSearch(values)}
                    onReset={() => this.onReset()}
                ></TheQueryForm>
                <TheTableExtend
                    columns={columns}
                    onFormTrigger={() => this.setState({form_show: !this.state.form_show})}
                    onTableRefresh={() => {
                        return dataSource
                    }}
                    onColumnsFilter={(value) => this.onColumnsFilter(value)}
                >
                    <TheButton type="primary" size="middle" onClick={this.openModal}>新增品种</TheButton>
                </TheTableExtend>
                <div className="p-layout-content-pagination">
                    <TheTable
                        scroll={{x: "max-content", y: "55vh"}}
                        columns={newColumns}
                        dataSource={dataSource}
                        rowKey={'petSpeciesId'}
                    />
                    <ThePagination
                        pageNo={pageData.pageNo}
                        pageSize={pageData.pageSize}
                        total={total}
                        pageChange={this.pageChange}
                    />
                </div>
                <Modal
                    title={title}
                    maskClosable={false}
                    visible={visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                >
                    <Form
                        name="basic"
                        labelCol={{
                            span: 6,
                        }}
                        wrapperCol={{
                            span: 14,
                        }}
                        ref={this.FormRef}
                        autoComplete="off"
                    >
                        <Form.Item
                            label="名称"
                            name="speciesName"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入名称',
                                },
                            ]}
                        >
                            <Input onKeyDown={(e)=>handleKeydown(e)} placeholder={'最多允许输入10个字'} maxLength={10}/>
                        </Form.Item>
                        <Form.Item
                            name="sorting"
                            label="排序"
                            getValueProps={v => ({value: v === 999999999?undefined:v, v})}
                        >
                            <InputNumber placeholder="请输入排序" min={1} max={9999} precision={0}/>
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        )
    }
}
